package com.aipartner.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * AI图片WebSocket服务器
 * 用于实时推送新上传的作品
 */
@ServerEndpoint("/ws/ai-image")
@Component
@Slf4j
public class AiImageWebSocketServer {

    // 静态变量，用来记录当前在线连接数
    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    
    // concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象
    private static final ConcurrentHashMap<String, AiImageWebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    
    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    
    // 接收sessionId
    private String sessionId = "";
    
    private static final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule())
            .disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        this.sessionId = session.getId();
        
        if (webSocketMap.containsKey(sessionId)) {
            webSocketMap.remove(sessionId);
        }
        webSocketMap.put(sessionId, this);
        
        int count = onlineCount.incrementAndGet();
        log.info("AI图片WebSocket连接建立: sessionId={}, 当前在线人数: {}", sessionId, count);
        
        try {
            sendMessage("{\"type\":\"connected\",\"message\":\"连接成功\"}");
        } catch (IOException e) {
            log.error("发送连接成功消息失败", e);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(sessionId)) {
            webSocketMap.remove(sessionId);
            int count = onlineCount.decrementAndGet();
            log.info("AI图片WebSocket连接关闭: sessionId={}, 当前在线人数: {}", sessionId, count);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自客户端{}的消息: {}", sessionId, message);
        
        try {
            // 可以在这里处理客户端发送的消息，比如心跳检测
            if ("ping".equals(message)) {
                sendMessage("pong");
            }
        } catch (IOException e) {
            log.error("回复客户端消息失败", e);
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("AI图片WebSocket发生错误: sessionId={}", sessionId, error);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        synchronized (this.session) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 广播消息给所有连接的客户端
     */
    public static void broadcastMessage(String message) {
        log.info("广播消息给{}个客户端: {}", webSocketMap.size(), message);
        
        for (AiImageWebSocketServer item : webSocketMap.values()) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                log.error("广播消息失败: sessionId={}", item.sessionId, e);
            }
        }
    }
    
    /**
     * 广播新作品信息
     */
    public static void broadcastNewExample(Object example) {
        try {
            String message = objectMapper.writeValueAsString(new WebSocketMessage("new_example", example));
            broadcastMessage(message);
        } catch (Exception e) {
            log.error("广播新作品失败", e);
        }
    }
    
    /**
     * WebSocket消息格式
     */
    public static class WebSocketMessage {
        private String type;
        private Object data;
        
        public WebSocketMessage(String type, Object data) {
            this.type = type;
            this.data = data;
        }
        
        // getters and setters
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        public Object getData() { return data; }
        public void setData(Object data) { this.data = data; }
    }
    
    /**
     * 获取当前在线人数
     */
    public static int getOnlineCount() {
        return onlineCount.get();
    }
}
